package com.mingchuang.administrator.mingchuang;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.mingchuang.administrator.mingchuang.bean.PileInfoBean;
import com.mingchuang.administrator.mingchuang.utils.Constant;
import com.mingchuang.administrator.mingchuang.utils.Util;
import com.mingchuang.administrator.mingchuang.xml.PileXml;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 定位 获取GPS
 */
public class GetLocationActivity extends AppCompatActivity implements View.OnClickListener, LocationSource,AMapLocationListener{

    private Button getBtn;
    private Button saveBtn;
    private TextView locationInfo;
    private MapView mapView;
    private AMap aMap;


    private String x;
    private String y;

    private ProgressDialog dialog;


    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;

    private OnLocationChangedListener mListener;

    private String path ;
    private int id;
    private PileInfoBean pileInfo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.location_layout);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);
        path = getIntent().getStringExtra("path");
        id = getIntent().getIntExtra("id",0);
        pileInfo = (PileInfoBean) getIntent().getSerializableExtra("pileInfo");
        intView();
        initMap();


    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    private void initMap() {
        //地图显示
        aMap = mapView.getMap();
        aMap.setLocationSource(this);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        //设置缩放比例
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));

        // 自定义系统定位蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.obd_map_marker_check));
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);


        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);


        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //开始定位
        mLocationClient.startLocation();


    }

    private void intView() {

        //显示定位dialog
        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setTitle("定位");
        dialog.setMessage("正在获取位置");
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();





        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("获取GPS信息");


        actionBar.show();

        getBtn = (Button) findViewById(R.id.get_gps);
        saveBtn = (Button) findViewById(R.id.save_gps);
        getBtn.setOnClickListener(this);
        saveBtn.setOnClickListener(this);
        locationInfo = (TextView) findViewById(R.id.location_info);



    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;

            default:
                break;
        }
        return super.onOptionsItemSelected(item);




    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.get_gps:
                //启动定位
                mLocationClient.startLocation();
                break;
            case R.id.save_gps:

                save2Xml();
                break;
            default:
                break;
        }


    }

    private void save2Xml() {

       if(!Util.checkIsNull(x) && !Util.checkIsNull(y)){
           if(PileXml.createXml(path+"/gps.xml", x, y)){
               //pileInfo.setIsGps("1");
               DbUtils db = AppApplication.getDb();
               try {
                   //db.save(pileInfo);
                   String sql = "update PileInfoBean set isGps = '1'where id= "+id;
                           //UPDATE Person SET FirstName = 'Fred' WHERE LastName = 'Wilson'

                   db.execNonQuery(sql);
               } catch (DbException e) {
                   e.printStackTrace();
               }
               Toast.makeText(this, "保存成功" ,Toast.LENGTH_SHORT).show();
               finish();

           }else{
               Toast.makeText(this, "保存失败，清稍后重试" ,Toast.LENGTH_SHORT).show();
           }

       }else{
           Toast.makeText(this , "正在定位" , Toast.LENGTH_SHORT).show();
       }


    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {

        mListener = onLocationChangedListener;


    }

    @Override
    public void deactivate() {

    }


    @Override
    public void onLocationChanged(AMapLocation amapLocation) {

        {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {

                    dialog.dismiss();
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    y = amapLocation.getLatitude() +"";//获取纬度
                    x = amapLocation.getLongitude() +"";//获取经度
                    amapLocation.getAccuracy();//获取精度信息
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(amapLocation.getTime());
                    df.format(date);//定位时间
                    amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果
                    amapLocation.getCountry();//国家信息
                    amapLocation.getProvince();//省信息
                    amapLocation.getCity();//城市信息
                    amapLocation.getDistrict();//城区信息
                    amapLocation.getRoad();//街道信息
                    amapLocation.getCityCode();//城市编码
                    amapLocation.getAdCode();//地区编码
                    locationInfo.setText("坐标："+x +"," + y);

                    mListener.onLocationChanged(amapLocation);// 显示系统小蓝点

                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }


        }

    }
}
